import upload from '@/components/AnswerSystem/Dashboard/upload';
import { MESSAGE_TYPE } from '../../../const';

const picStatus = {
  pending: 'pending',
  resolve: 'resolve',
  reject: 'reject',
};
class PastPicture {
  constructor({
    currentPictureList = [],
    allPicHasUpload = false,
    hasTrigger = false,
  } = {}) {
    this.currentPictureList = currentPictureList; // 保存图片url和key
    this.allPicHasUpload = allPicHasUpload; // 表示是否当亲所有图片都上传CDN
    this.hasTrigger = hasTrigger; // 是否在所有上传图片请求返回是，自动触发发送函数
  }

  // 粘贴图片调用参数，在粘贴后，立即上传至cdn，并将url，key保存在currentPictureList中
  addPicture=({
    file, user, key, progress,
  }) => {
    this.hasTrigger = false;
    return new Promise((resolve, reject) => {
      const picture = {
        key,
        status: picStatus.pending,
        url: '',
      };
      this.allPicHasUpload = false;
      this.currentPictureList.push(picture);
      upload({
        file,
        user,
        progress,
        key,
      }).then(({ data: { data } }) => {
        picture.status = picStatus.resolve;
        picture.url = data.url;
        this.checkAllStatusExecuteCallback();
        resolve({ file, data });
      }).catch(() => {
        picture.status = picStatus.reject;
        this.checkAllStatusExecuteCallback();
        // eslint-disable-next-line
        reject({file});
      });
    });
  };

  // 执行传入的回复的函数
  // this.arguments结构[{message: string,id:number,type:number,ct:number}]
  ExecuteCallback=() => {
    if (!Array.isArray(this.callbackArg) || !this.callbackArg.length) {
      return;
    }

    this.callbackFun({
      list: this.callbackArg.reduce((pre, cur) => {
        const { type, id, ct } = cur;
        if (type === MESSAGE_TYPE.TEXT.VAL) {
          return [...pre, {
            id,
            type,
            ct,
            message: cur.message,
          }];
        } if (type === MESSAGE_TYPE.IMAGE.VAL) {
          const item = this.currentPictureList.find(x => x.key === parseInt(cur.message, 10));
          return [...pre, {
            id,
            type,
            ct,
            message: item && item.status === picStatus.resolve && item.url ? item.url : '',
          }];
        } return pre;
      }, []),
    }, ...this.otherParams).then((...rest) => {
      this.successFunc(...rest);
      this.reset();
    }).catch((...rest) => {
      this.errorFunction && this.errorFunction(...rest);
      this.reset();
    });
  };

  // 重置当前的图片列表，以及状态
  reset=() => {
    this.currentPictureList = [];
    this.allPicHasUpload = false;
    this.hasTrigger = false;
    return this;
  };

  // 回复消息的函数
  trigger=(func, funcArguments, ...otherParams) => {
    this.hasTrigger = true;
    this.callbackFun = func;
    this.callbackArg = funcArguments;
    this.otherParams = otherParams;
    // 所有图片已经上传完成，包括失败，
    if (this.allPicHasUpload || this.currentPictureList.length === 0) {
      this.ExecuteCallback();
    }
    return this;
  };

  // 检查图片列表的状态，如果已经点击过发送，则触发回调函数
  checkAllStatusExecuteCallback=() => {
    this.allPicHasUpload = true;
    if (this.hasTrigger
      && !this.currentPictureList.find(item => item.status === picStatus.pending)) {
      // 所有上传图片都完成
      this.ExecuteCallback();
    }
    return this;
  };

  // 传入一个函数，回调函数执行成功后调用
  then=(successFunc) => {
    this.successFunc = successFunc;
    return this;
  }

  // 传入一个函数，回调函数执行失败的时候调用
  catch=(errorFunction) => {
    this.errorFunction = errorFunction;
    return this;
  }
}

export default PastPicture;
